import os
import sys
import logging
import subprocess
import threading
import time
from flask import Flask, request, jsonify
from flask_cors import CORS
from flask_jwt_extended import JWTManager
import sqlite3

# 配置日志记录
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


# 添加项目根目录到Python路径
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

from db.db_helpers import init_db, query_db, execute_db, get_db_connection
from api.questions import questions_bp
from api.analytics import analytics_bp
from api.auth import auth_bp

# 尝试导入外部AI服务
try:
    from api.external_ai import external_ai_bp
    EXTERNAL_AI_AVAILABLE = True
except ImportError:
    EXTERNAL_AI_AVAILABLE = False

# 尝试导入新增模块
try:
    from api.student.path import path_bp
    from api.student.exercises import exercises_bp
    from api.teacher.assessment import assessment_bp
    from api.teacher.classes import classes_bp
    from api.offline import offline_bp
    NEW_MODULES_AVAILABLE = True
except ImportError as e:
    NEW_MODULES_AVAILABLE = False
    logger.warning(f"新模块导入失败: {e}")

app = Flask(__name__)
CORS(app)

# JWT配置
app.config['JWT_SECRET_KEY'] = 'zhixiban-secret-key'
app.config['JWT_TOKEN_LOCATION'] = ['headers']
app.config['JWT_HEADER_NAME'] = 'Authorization'
app.config['JWT_HEADER_TYPE'] = 'Bearer'
jwt = JWTManager(app)

# 注册蓝图
app.register_blueprint(auth_bp, url_prefix='/api/auth')
app.register_blueprint(questions_bp, url_prefix='/api/questions')
app.register_blueprint(analytics_bp, url_prefix='/api/analytics')
if EXTERNAL_AI_AVAILABLE:
    app.register_blueprint(external_ai_bp, url_prefix='/api/external-ai')
    
# 注册新增蓝图
if NEW_MODULES_AVAILABLE:
    app.register_blueprint(path_bp, url_prefix='/api/student')
    app.register_blueprint(exercises_bp, url_prefix='/api/student')
    app.register_blueprint(assessment_bp, url_prefix='/api/teacher')
    app.register_blueprint(classes_bp, url_prefix='/api/teacher')
    app.register_blueprint(offline_bp, url_prefix='/api')

@app.route('/')
def home():
    return jsonify({"message": "欢迎使用智习伴API服务"}), 200


def init_database():
    """初始化数据库"""
    try:
        init_db()
        logger.info("数据库初始化完成")
    except Exception as e:
        logger.error(f"数据库初始化失败: {e}")

# 健康检查端点
@app.route('/health')
def health_check():
    """健康检查"""
    try:
        # 检查数据库连接
        conn = get_db_connection()
        conn.execute('SELECT 1')
        conn.close()
        
        return jsonify({
            "status": "healthy",
            "timestamp": time.time(),
            "services": {
                "database": "connected",
                "backend": "running on port 5000",
                "frontend": "configured for port 8001"
            }
        }), 200
    except Exception as e:
        logger.error(f"健康检查失败: {str(e)}")
        return jsonify({
            "status": "unhealthy",
            "error": str(e)
        }), 500

# 启动前端服务
@app.route('/start-frontend', methods=['POST'])
def start_frontend_service():
    """启动前端服务"""
    try:
        # 获取项目根目录
        project_root = os.path.join(os.path.dirname(__file__), '..')
        frontend_dir = os.path.join(project_root, 'frontend')
        
        # 检查前端目录是否存在
        if not os.path.exists(frontend_dir):
            return jsonify({"error": "前端目录不存在"}), 404
            
        def run_frontend():
            try:
                # 启动HTTP服务器
                subprocess.Popen([
                    sys.executable, '-m', 'http.server', '8001'
                ], cwd=frontend_dir)
                logger.info("前端服务启动成功")
                logger.info("前端服务地址: http://localhost:8001")
            except Exception as e:
                logger.error(f"前端服务启动失败: {str(e)}")
        
        # 启动前端服务线程
        frontend_thread = threading.Thread(target=run_frontend)
        frontend_thread.daemon = True
        frontend_thread.start()
        
        return jsonify({
            "message": "前端服务启动命令已发送", 
            "status": "success", 
            "url": "http://localhost:8001"
        }), 200
    except Exception as e:
        logger.error(f"启动前端服务时出错: {str(e)}")
        return jsonify({"error": f"启动前端服务失败: {str(e)}"}), 500

if __name__ == '__main__':
    # 初始化数据库
    init_database()
    
    # 启动Flask应用
    app.run(host='0.0.0.0', port=5000, debug=True)